package cn.xspace.wnx.activity;

import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.maps2d.AMap;
import com.amap.api.maps2d.CameraUpdateFactory;
import com.amap.api.maps2d.LocationSource;
import com.amap.api.maps2d.MapView;
import com.amap.api.maps2d.model.BitmapDescriptorFactory;
import com.amap.api.maps2d.model.CameraPosition;
import com.amap.api.maps2d.model.LatLng;
import com.amap.api.maps2d.model.Marker;
import com.amap.api.maps2d.model.MarkerOptions;
import com.amap.api.services.core.AMapException;
import com.amap.api.services.core.LatLonPoint;
import com.amap.api.services.core.PoiItem;
import com.amap.api.services.help.Inputtips;
import com.amap.api.services.help.InputtipsQuery;
import com.amap.api.services.help.Tip;
import com.amap.api.services.poisearch.PoiResult;
import com.amap.api.services.poisearch.PoiSearch;
import com.xspace.android.xafcommon.base.BaseActivity;
import com.xspace.android.xafcommon.util.EventBusConstant;
import com.xspace.android.xafcommon.util.LogUtil;
import com.xspace.android.xafcommon.util.T;
import com.xspace.android.xafcommon.view.XListView;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import cn.xspace.app.view.TitleBar;
import cn.xspace.wnx.R;
import cn.xspace.wnx.adapter.MapSearchListAdapter;
import de.greenrobot.event.EventBus;

public class MapLocationSearchActivity extends BaseActivity implements AMap.OnCameraChangeListener,
        AMapLocationListener, TextWatcher, Inputtips.InputtipsListener, XListView.IXListViewListener, LocationSource {

    public static final String TAG = MapLocationSearchActivity.class.getSimpleName();

    private TitleBar mTitleBar;
    private RelativeLayout mRelativeSearch;
    private LinearLayout mLayoutSearch;
    private AutoCompleteTextView mEtMapSearch;
    private TextView mTvMapSearch;
    private RelativeLayout mRelativeMap;
    private AMap aMap;
    private MapView mapView;
    private ImageView mIvCenter;
    private XListView mXLvMapResult;
    private RelativeLayout mRelativeProgress;
    private MapSearchListAdapter mAdapter;

    private AMapLocationClient mLocationClient;
    private AMapLocation mAmapLocation;
    //    private String ipoStr = "政府机构及社会团体|公司企业|道路附属设施|地名地址信息|公共设施";
    private String ipoStr =
            "汽车服务|汽车销售|汽车维修|摩托车服务|餐饮服务|购物服务|生活服务|体育休闲服务|医疗保健服务|住宿服务|风景名胜|商务住宅|政府机构及社会团体|科教文化服务|交通设施服务|金融保险服务|公司企业|道路附属设施|地名地址信息|公共设施";

    private OnLocationChangedListener mListener;
    private Marker locationMarker;
    private LatLng locationLatLng;
    private boolean mIsLoadMore;

    private static final int RE_SEARCH = 1;
    private static final int SEARCH_MORE = 2;
    private boolean isSearchResult; //是否是搜索列表

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_map_loaction_search);
        mTitleBar = (TitleBar) findViewById(R.id.map_search_title_bar);
        //搜索布局
        mRelativeSearch = (RelativeLayout) findViewById(R.id.layout_map_search_click);//搜索框点击
        mLayoutSearch = (LinearLayout) findViewById(R.id.layout_map_search_edit);//搜索框编辑
        mRelativeMap = (RelativeLayout) findViewById(R.id.relative_map);//搜索框点击
        mEtMapSearch = (AutoCompleteTextView) findViewById(R.id.et_map_search);
        mTvMapSearch = (TextView) findViewById(R.id.tv_map_search);
        mapView = (MapView) findViewById(R.id.a_map_view);
        mIvCenter = (ImageView) findViewById(R.id.iv_map_center);
        //结果布局
        mXLvMapResult = (XListView) findViewById(R.id.xlv_map_search_result);
        mRelativeProgress = (RelativeLayout) findViewById(R.id.relative_map_progress_bar);//搜索框点击
        mapView.onCreate(savedInstanceState);// 此方法必须重写

        mAdapter = new MapSearchListAdapter(mContext, mDataList);
        mXLvMapResult.setAdapter(mAdapter);
        mXLvMapResult.setXListViewListener(this);
        mXLvMapResult.setPullLoadEnable(true);
        mXLvMapResult.setPullRefreshEnable(false);
        initMap();
        initEventNew();
    }

    /**
     * 方法必须重写
     */
    @Override
    protected void onResume() {
        super.onResume();
        mapView.onResume();
    }

    /**
     * 方法必须重写
     */
    @Override
    protected void onPause() {
        super.onPause();
        mapView.onPause();
        deactivate();
    }

    /**
     * 方法必须重写
     */
    @Override
    protected void onDestroy() {
        super.onDestroy();
        mapView.onDestroy();
        if (null != mLocationClient) {
            mLocationClient.onDestroy();
        }
    }

    /**
     * 方法必须重写
     */
    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        mapView.onSaveInstanceState(outState);
    }

    /**
     * 初始化
     */
    private void initMap() {
        if (aMap == null) {
            aMap = mapView.getMap();
            setUpMap();
        }
    }

    protected void setUpMap() {
        aMap.setOnCameraChangeListener(this);
//        aMap.setInfoWindowAdapter(infoWindowAdapter);
        aMap.setLocationSource(this);// 设置定位监听
        aMap.getUiSettings().setMyLocationButtonEnabled(true);// 设置默认定位按钮是否显示
        aMap.setMyLocationEnabled(true);// 设置为true表示显示定位层并可触发定位，false表示隐藏定位层并不可触发定位，默认是false

    }

    protected void initEventNew() {
        mTitleBar.setLeftLayoutClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                actionBackPress();
            }
        });
        mRelativeSearch.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showSearchLayout();
            }
        });
        mTitleBar.setRightLayoutClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

            }
        });
        mTvMapSearch.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String keyWord = mEtMapSearch.getText().toString().trim();
                if (TextUtils.isEmpty(keyWord)) {
                    T.showSingleL("请输入搜索关键字");
                } else {
                    doSearchQuery(keyWord, null);
                }
            }
        });
        mEtMapSearch.addTextChangedListener(this);// 添加文本输入框监听事件
        mXLvMapResult.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                PoiItem poiItem = mDataList.get(position - mXLvMapResult.getHeaderViewsCount());
                LatLonPoint latLonPoint = poiItem.getLatLonPoint();
                if (mLayoutSearch.getVisibility() == View.VISIBLE) { //在搜索界面
                    actionBackPress();
                    isSearchResult = true;
                    aMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(latLonPoint.getLatitude(),
                            latLonPoint.getLongitude()), 18));
                } else {
                    HashMap<String, Object> eventMap = new HashMap<>();
                    eventMap.put(EventBusConstant.TYPE, TAG);
                    eventMap.put(EventBusConstant.ACTION_KEY, poiItem);
                    EventBus.getDefault().post(eventMap);
                    actionBackPress();
                }
            }
        });
    }

    private void showSearchLayout() {
        mRelativeSearch.setVisibility(View.GONE);
        mLayoutSearch.setVisibility(View.VISIBLE);
        mRelativeMap.setVisibility(View.GONE);
    }

    private void hiddenSearchLayout() {
        mEtMapSearch.setText("");
        mRelativeSearch.setVisibility(View.VISIBLE);
        mLayoutSearch.setVisibility(View.GONE);
        mRelativeMap.setVisibility(View.VISIBLE);
    }

    private void actionBackPress() {
        if (mLayoutSearch.getVisibility() == View.VISIBLE) {
            hiddenSearchLayout();
        } else {
            finish();
        }
    }

    @Override
    public void onBackPressed() {
        actionBackPress();
    }

    //激活定位
    @Override
    public void activate(OnLocationChangedListener onLocationChangedListener) {
        mListener = onLocationChangedListener;
        if (mLocationClient == null) {
            mLocationClient = new AMapLocationClient(this);
            AMapLocationClientOption mLocationOption = new AMapLocationClientOption();
            //设置定位监听
            mLocationClient.setLocationListener(this);
            //设置为高精度定位模式
            mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
            //设置定位参数
            mLocationClient.setLocationOption(mLocationOption);
            // 此方法为每隔固定时间会发起一次定位请求，为了减少电量消耗或网络流量消耗，
            // 注意设置合适的定位时间的间隔（最小间隔支持为2000ms），并且在合适时间调用stopLocation()方法来取消定位请求
            // 在定位结束后，在合适的生命周期调用onDestroy()方法
            // 在单次定位情况下，定位无论成功与否，都无需调用stopLocation()方法移除请求，定位sdk内部会移除
            mLocationClient.startLocation();
        }
    }

    //停止定位
    @Override
    public void deactivate() {
        mListener = null;
        if (mLocationClient != null) {
            mLocationClient.stopLocation();
            mLocationClient.onDestroy();
        }
        mLocationClient = null;
    }

    //获取到定位位置
    @Override
    public void onLocationChanged(AMapLocation aMapLocation) {
        if (mListener != null) {
            // 此处注释掉，表示不用系统提供的定位图标等
            mListener.onLocationChanged(aMapLocation);
        }
        if (aMapLocation != null) {
            mAmapLocation = aMapLocation;
            aMap.moveCamera(CameraUpdateFactory.zoomTo(18));
//            doSearchQuery(mAmapLocation.getPoiName(), 0, RE_SEARCH);
        }
        deactivate();
    }

    @Override
    public void onCameraChangeFinish(CameraPosition position) {
        LogUtil.d(TAG, "wubaojie>>>onCameraChangeFinish");
        if (isSearchResult) {
            isSearchResult = false;
        } else {
            LatLng latLng = position.target;
            doSearchQuery("", new LatLonPoint(latLng.latitude, latLng.longitude));
        }
//        Observable.create(new Observable.OnSubscribe<RegeocodeAddress>() {
//            @Override
//            public void call(Subscriber<? super RegeocodeAddress> subscriber) {
//                GeocodeSearch geocodeSearch = new GeocodeSearch(mContext);
//                LatLonPoint point = new LatLonPoint(latLng.latitude, latLng.longitude);
//                RegeocodeQuery regeocodeQuery = new RegeocodeQuery(point, 1000, GeocodeSearch.AMAP);
//                RegeocodeAddress address;
//                try {
//                    address = geocodeSearch.getFromLocation(regeocodeQuery);
//                    subscriber.onNext(address);
//                } catch (AMapException e) {
//                    subscriber.onError(e);
//                }
//                subscriber.onCompleted();
//            }
//        }).subscribeOn(Schedulers.io())
//                .observeOn(AndroidSchedulers.mainThread()).subscribe(new Subscriber<RegeocodeAddress>() {
//            @Override
//            public void onCompleted() {
//            }
//
//            @Override
//            public void onError(Throwable throwable) {
//                throwable.printStackTrace();
//            }
//
//            @Override
//            public void onNext(RegeocodeAddress address) {
//                if (address != null) {
////                    doSearchQuery(address.getNeighborhood(), 0, RE_SEARCH);
//                    List<PoiItem> pois = address.getPois();
//                    mDataList.clear();
//                    mDataList.addAll(pois);
//                    refreshList();
//                }
////                    if (null != address) {
////                        locationMarker.setSnippet(address.getFormatAddress());
////                    }
////                    locationMarker.showInfoWindow();
//            }
//        });
    }

    private void jumpLogo() {
//        ViewHelper.setTranslationY(mIvCenter, mIvCenter.getMeasuredHeight() - 50);
//        ViewPropertyAnimator.animate(mIvCenter).translationYBy(50).setDuration(400)
//                .setInterpolator(new OvershootInterpolator()).start();
    }

    @Override
    public void onCameraChange(CameraPosition position) {
        LogUtil.d(TAG, "wubaojie>>>onCameraChange");
//        if (locationMarker != null) {
//            LatLng latLng = position.target;
//            locationMarker.setPosition(latLng);
//        }
    }

    /**
     * 开始搜索周边
     */
    private PoiSearch.Query query;
    private int currentPage;
    private PoiSearch poiSearch;
    private PoiResult poiResult;
    private List<PoiItem> mDataList = new ArrayList<>();

    /**
     * 开始进行poi搜索
     */
    protected void doSearchQuery(String keyWord, LatLonPoint bound) {
        LogUtil.d("wubaojie>>>doSearchQuery: keyWork:" + keyWord);
        mXLvMapResult.setPullLoadEnable(true);
        currentPage = 0;
        mDataList.clear();
        mAdapter.notifyDataSetChanged();
        mRelativeProgress.setVisibility(View.VISIBLE);
        // 第一个参数表示搜索字符串，第二个参数表示poi搜索类型，第三个参数表示poi搜索区域（空字符串代表全国）
        query = new PoiSearch.Query(keyWord, ipoStr, mAmapLocation.getCityCode());//
        query.setPageSize(10);// 设置每页最多返回多少条poiitem
        query.setPageNum(currentPage);// 设置查第一页
        query.setCityLimit(true);
        poiSearch = new PoiSearch(this, query);
        poiSearch.setOnPoiSearchListener(onPoiSearchListener);
        // 设置搜索区域为以lp点为圆心，其周围500米范围
        if (bound != null) {
            poiSearch.setBound(new PoiSearch.SearchBound(bound, 500, true));
        }
//        else {
//            poiSearch.setBound(new PoiSearch.SearchBound(new LatLonPoint(mAmapLocation.getLatitude(), mAmapLocation
//                    .getLongitude()), 500, true));
//        }
        poiSearch.searchPOIAsyn();
    }

    PoiSearch.OnPoiSearchListener onPoiSearchListener = new PoiSearch.OnPoiSearchListener() {
        @Override
        public void onPoiSearched(PoiResult result, int rCode) {
            hideWaitDialog();
//            hiddenSearchLayout();
            if (rCode == AMapException.CODE_AMAP_SUCCESS) {
                if (result != null && result.getQuery() != null) {// 搜索poi的结果
                    poiResult = result;
                    // 取得搜索到的poiItems有多少页
                    List<PoiItem> poiItems = poiResult.getPois();// 取得第一页的poiItems数据，页数从数字0开始
                    if (result.getQuery().equals(query)) {// 是否是同一条
                        // 当搜索不到poiItems数据时，会返回含有搜索关键字的城市信息
//                        List<SuggestionCity> suggestionCities = poiResult.getSearchSuggestionCitys();

                        if (poiItems != null && poiItems.size() > 0) {
                            mDataList.addAll(poiItems);
//                            aMap.clear();// 清理之前的图标
//                            PoiOverlay poiOverlay = new PoiOverlay(aMap, poiItems);
//                            poiOverlay.removeFromMap();
//                            poiOverlay.addToMap();
//                            poiOverlay.zoomToSpan();
                        }/* else if (suggestionCities != null && suggestionCities.size() > 0) {
                            showSuggestCity(suggestionCities);
                        }*/ else {
                            T.showSingleL("没有结果");
                        }
                    } else { //不是同一条
                        if (poiItems != null && poiItems.size() > 0) {
                            mDataList.addAll(poiItems);
                        } else {
                            T.showSingleL("没有更多结果");
                            mXLvMapResult.setPullLoadEnable(false);
                        }
                    }
                } else {
                    T.showSingleL("没有结果");
                }
            } else {
                T.showSingleL("请求失败");
            }
            refreshList();
        }

        @Override
        public void onPoiItemSearched(PoiItem poiItem, int i) {

        }
    };

    private void refreshList() {
//        mPullToRefreshListView.onRefreshComplete();
        if (mAdapter != null) {
            mXLvMapResult.stopRefresh();
            mXLvMapResult.stopLoadMore();
            mAdapter.notifyDataSetChanged();
            mIsLoadMore = false;
            mRelativeProgress.setVisibility(View.GONE);
        }
    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {

    }

    @Override
    public void afterTextChanged(Editable s) {
        String newText = s.toString().trim();
        if (!TextUtils.isEmpty(newText)) {
            InputtipsQuery inputQuery = new InputtipsQuery(newText, mAmapLocation.getCityCode());
            Inputtips inputTips = new Inputtips(mContext, inputQuery);
            inputTips.setInputtipsListener(this);
            inputTips.requestInputtipsAsyn();
        }
    }

    @Override
    public void onGetInputtips(List<Tip> tipList, int rCode) {
        if (rCode == AMapException.CODE_AMAP_SUCCESS) {// 正确返回
            List<String> listString = new ArrayList<String>();
            for (int i = 0; i < tipList.size(); i++) {
                listString.add(tipList.get(i).getName());
            }
            ArrayAdapter<String> aAdapter = new ArrayAdapter<>(mContext, android.R.layout.simple_list_item_1,
                    listString);
            mEtMapSearch.setAdapter(aAdapter);
            aAdapter.notifyDataSetChanged();
        } else {
            T.showSingleL("没有数据");
        }
    }

    @Override
    public void onRefresh() {

    }

    @Override
    public void onLoadMore() {
        if (!mIsLoadMore) {
            queryNext();
        }
    }

    public void queryNext() {
        if (query != null && poiSearch != null && poiResult != null) {
            if (poiResult.getPageCount() - 1 > currentPage) {
                currentPage++;
                query.setPageNum(currentPage);// 设置查后一页
                poiSearch.searchPOIAsyn();
            } else {
                mXLvMapResult.setPullLoadEnable(false);
                T.showSingleL("没有更多结果");
            }
        }
    }

    AMap.InfoWindowAdapter infoWindowAdapter = new AMap.InfoWindowAdapter() {

        @Override
        public View getInfoWindow(Marker marker) {
            return null;
        }

        @Override
        public View getInfoContents(Marker marker) {
            View mContents = getLayoutInflater().inflate(R.layout.custom_info_contents, null);
            render(marker, mContents);
            return mContents;
        }
    };

    /**
     * 自定义infowindow的样式
     */
    public void render(Marker marker, View view) {
        String title = marker.getTitle();
        TextView titleUi = ((TextView) view.findViewById(R.id.title));
        if (title != null) {
            titleUi.setText(title);
        } else {
            titleUi.setText("");
        }
        String snippet = marker.getSnippet();
        TextView snippetUi = ((TextView) view.findViewById(R.id.snippet));
        if (snippet != null) {
            snippetUi.setText(snippet);
        } else {
            snippetUi.setText("");
        }
    }

    /**
     * 往地图上添加marker
     *
     * @param latLng
     */
    private void addMarker(LatLng latLng, String desc) {
        MarkerOptions markerOptions = new MarkerOptions();
        markerOptions.position(latLng);
        markerOptions.title("[我的位置]");
        markerOptions.snippet(desc);
        markerOptions.icon(BitmapDescriptorFactory.defaultMarker());
        locationMarker = aMap.addMarker(markerOptions);
    }
}
